package com.tavio.vaultboy.element;

import org.andengine.opengl.vbo.VertexBufferObjectManager;

import com.tavio.vaultboy.collision.Face;
import com.tavio.vaultboy.controller.Controller;
import com.tavio.vaultboy.element.type.ElementType;
import com.tavio.vaultboy.scene.SceneManager;


public class Button extends RectangleElement {
	
	public Face touchableFace;
	
	public Door connectedDoor;
	
	private float oldY;
	
	private float oldX;
	
	private boolean collided = false;
	
	private boolean doorWasRemoved = false;
	
	public Button(Face touchableFace, float x, float y, float width, float height,
			VertexBufferObjectManager vertexBufferObjectManager) {
		super(ElementType.BUTTON, x, y, width, height, vertexBufferObjectManager);
		this.touchableFace = touchableFace;
	}

	@Override
	public void updatePositionAndCheckCollisions(float timeElapsed) {
		
		oldY = this.y;
		oldX = this.x;
		
		switch(touchableFace) {
			case UP:
				this.y = getBoundingBox().top - 1;
				break;
			case RIGHT:
				this.x = getBoundingBox().right + 1;
				break;
			case DOWN:
				this.y = getBoundingBox().top + 1;
				break;
			case LEFT:
				this.x = getBoundingBox().right - 1;
				break;
		}
		getBoundingBox().update();
		
		for(Element element : SceneManager.getInstance().collidableElements) {
			if(! this.equals(element) &&
					(ElementType.BOX.equals(element.elementType) || ElementType.VAULT_BOY.equals(element.elementType)) &&
					getBoundingBox().collidesWith(element.getBoundingBox())) {
				collided = true;
				break;
			}
		}
		
		if(collided) {
			SceneManager.getInstance().removeDoorFromScene(connectedDoor);
			doorWasRemoved = true;
		} else if(doorWasRemoved) {
			SceneManager.getInstance().addDoorToScene(connectedDoor);
			doorWasRemoved = false;
		}
			
		
		this.x = oldX;
		this.y = oldY;
		
		getBoundingBox().update();
		
		collided = false;
		
	}
		
}
